const { app, session } = require('electron');
const path = require('path');
const { openByUrl } = require('./protocol');

app.whenReady().then(() => {
    session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
        if (details.url === 'https://snapabug.appspot.com/snapabug-testsys.js') {
            callback({ cancel: true });
            return;
        }
        callback({ cancel: false });
    });


    session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
        const ua = details.requestHeaders['User-Agent'];
        details.requestHeaders['User-Agent'] = createUserAgent(ua);
        callback({ cancel: false, requestHeaders: details.requestHeaders });
    });

    session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
        const contenttype = details.responseHeaders['Content-Type'];

        if ((contenttype || '').includes("application/pdf")) {
            attachmentPdf(details, callback);
            return;
        } else if (details.statusCode === 302) {
            const result = openRoombox(details, callback);
            if (result) {
                return;
            }
        }

        callback({});
    });
});

function attachmentPdf(details, callback) {
    let filename = path.basename(details.url) || '';
    if (!filename) {
        filename = 'file.pdf';
    } else if (!filename.endsWith('.pdf')) {
        filename = `${filename}.pdf`;
    }

    const cd = details.responseHeaders['Content-Disposition'] || '';

    if (cd.includes('attachment')) {
        callback({});
    } else {
        callback({ responseHeaders: { "Content-Disposition": `attachment; filename="${filename}"` } });
    }
}

function openRoombox(details, callback) {
    const locations = details.responseHeaders['Location'];
    if (!locations || locations.length <= 0) {
        return false;
    }

    const url = locations[0];
    if (url.includes('livebroadcast') && url.includes('enter_roombox_room')) {
        const uRL = new URL(url, details.url);
        const invokeUrl = uRL.searchParams.get('invokeUrl');
        if (invokeUrl) {
            openByUrl(decodeURIComponent(invokeUrl));
            callback({ cancel: true });
            return true;
        }
    }

    return false;
}

var _userAgent;
function createUserAgent(ua) {
    if (_userAgent) {
        return _userAgent;
    }

    if (!ua) {
        return ua;
    }

    const appid = process.env.APP_ID;
    const version = process.env.APP_VERSION || '1.0.0';
    const ua_appname = process.env.UA_APP_NAME || 'k';
    const buildid = process.env.BUILD_ID || '0';

    if (process.env.UA_APP_NAME) {
        console.log('ua_appname:', process.env.UA_APP_NAME, ua_appname);
        buildid && console.log('buildid', process.env.BUILD_ID || '1');
    }

    //Mozilla/5.0 (Windows NT 10.0; Win64; x64; Koolearn; kooup/1.0.0; W/55/88) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.106 Electron/4.0.5 Safari/537.36
    var nua = /\([^)]*/.exec(ua);
    nua = `${nua}; Koolearn; ${ua_appname}/${version}; ${process.platform === 'win32' ? 'W' : 'M'}/${appid}/${buildid}`;
    nua = ua.replace(/\([^)]*/, nua);
    // nua = nua.replace(/electron\/.+\s/i, '');
    // nua = nua.replace(GLOBAL_APP_NAME, 'koolearn');
    appid && console.log(`UA:`, nua);
    if (appid) {
        _userAgent = nua;
    }

    return nua;
}